<template>
  <div class="user-info-container">
    <!-- 个人信息卡片 -->
    <el-card class="info-card" shadow="hover">
      <div class="avatar-container">
        <el-upload
          class="avatar-uploader"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :auto-upload="true"
        >
          <el-avatar 
            :size="120" 
            :src="userInfo.avatar === '' || userInfo.avatar === null ? require('@/assets/default_img.jpg') : userInfo.avatar"
            class="hover-effect"
          />
        </el-upload>
        <p class="username">{{ userInfo.nickName }}</p>
      </div>

      <div class="user-details">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="邮箱">
            <el-icon><Message /></el-icon>
            <span class="info-text">{{ userInfo.email }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="电话">
            <el-icon><Phone /></el-icon>
            <span class="info-text">{{ userInfo.phone }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="性别">
            <el-icon><User /></el-icon>
            <span class="info-text">{{ userInfo.sex }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="年龄">
            <el-icon><Calendar /></el-icon>
            <span class="info-text">{{ userInfo.age }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="角色">
            <el-icon><UserFilled /></el-icon>
            <span class="info-text">{{ userInfo.role }}</span>
            <el-link v-if="userInfo.role === '管理员'" type="primary" href="http://127.0.0.1:8081/" style="margin-left: 10px">进入后台管理</el-link>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <!-- 修改密码表单 -->
      <el-form :model="passwordForm" label-width="100px" class="password-form">
        <el-form-item label="原密码">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="新密码">
          <el-input v-model="passwordForm.newPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认新密码">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="updatePassword(userInfo.id)" :icon="Edit">修改密码</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 预约门票列表 -->
    <el-card class="ticket-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="header-title">我的预约</span>
        </div>
      </template>
      <el-empty v-if="!ticketList || ticketList.length === 0" description="您未预约任何门票哦！" />
      <el-table v-else :data="ticketList" style="width: 100%" stripe>
        <el-table-column prop="scenicName" label="景区名称" />
        <el-table-column prop="createTime" label="订单时间" />
        <el-table-column prop="totalAmount === 0 ? '免费' : '¥'+totalAmount" label="支付金额">
          <template #default="scope">
            <span>¥{{ scope.row.totalAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="支付状态">
          <template #default="scope">
            <el-tag :type="scope.row.state === 3 ? 'success' : scope.row.state === 2 ? 'info' : 'warning'">
              {{ scope.row.state === 3 ? '已支付' : scope.row.state === 2 ? '已取消' : '未支付' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="used" label="使用状态">
          <template #default="scope">
            <el-tag :type="scope.row.used ? 'success' : 'warning'">
              {{ scope.row.used ? '已使用' : '未使用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="订单二维码" width="100">
          <template #default="scope">
            <el-popover
              placement="right"
              trigger="click"
              width="200"
            >
              <template #reference>
                <el-button type="primary" size="small">查看二维码</el-button>
              </template>
              <div style="text-align: center">
                <img :src="scope.row.tcode" style="width: 150px; height: 150px"/>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button type="danger" size="small" @click="cancelBooking(scope.row)" :icon="Delete">取消预约</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 我的动态列表 -->
    <el-card class="post-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="header-title">我的动态</span>
        </div>
      </template>
      <el-empty v-if="!myPosts || myPosts.length === 0" description="您未发布任何动态哦！" />
      <div v-else v-for="post in myPosts" :key="post.id" class="post-item">
        <div class="post-content">{{ post.content }}</div>
        <div class="post-images" v-if="post.images.length">
          <el-image 
            v-for="(img, index) in post.images" 
            :key="index"
            :src="img"
            :preview-src-list="post.images"
            fit="cover"
            class="post-image"
          />
        </div>
        <div class="post-footer">
          <span class="post-time"><i class="el-icon-time"></i> 发布于{{ post.createTime }}</span>
          <span class="post-likes">
            {{ post.likeTotal }} 人点赞过
          </span>
          <el-button type="danger" size="small" @click="deletePost(post)" :icon="Delete">删除</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive,onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete } from '@element-plus/icons-vue'
import axios from 'axios'

export default {
  setup() {

    // 用户信息
    const userInfo = ref('')

    //加载用户信息
    onMounted(() => {
      const user = JSON.parse(sessionStorage.getItem('userInfo'))
      if(!user || user.length === 0 || user === null){
        ElMessage({
          message: '用户未登录！',
          type: 'warning',
        })
        window.location.href = '/'
      }else{
        userInfo.value = user
        getTicketList();
        getMyPosts();
      }
    })

    // 修改密码表单
    const passwordForm = reactive({
      userId: '',
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })

    // 预约列表
    const ticketList = ref([
      {
        scenicName: '西湖风景区',
        bookTime: '2024-01-25',
        status: '已预约'
      }
    ])

    // 我的动态列表
    const myPosts = ref([
      {
        id: 1,
        content: '今天游玩很开心！',
        images: ['https://example.com/image1.jpg'],
        createTime: '2024-01-20 15:30',
        likeTotal: 0
      }
    ])

    // 获取我的动态
    const getMyPosts = () => {
      axios.get('/api/blog/user/'+userInfo.value.id)
      .then(res => {
        if(res.data.code == 200){
          myPosts.value = res.data.data
        }else{
          ElMessage.error(res.data.message)
        }
      })
      .catch(err =>{
        ElMessage.error("我的动态加载失败")
      })
    }

    // 上传头像相关
    const uploadRef = ref(null)
    const handleAvatarClick = () => {
      uploadRef.value.click()
    }

    const beforeAvatarUpload = (file) => {
      const isJPG = file.type === 'image/jpeg'
      const isLt20M = file.size / 1024 / 1024 < 20

      if (!isJPG) {
        ElMessage.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt20M) {
        ElMessage.error('上传头像图片大小不能超过 20MB!')
      }

      // 创建 FormData 实例
      const formData = new FormData();
      formData.append('userId', userInfo.value.id);
      formData.append('avatar', file);

      // 通过 axios 上传文件
      axios.post('/api/user/change/avatar', formData, {
        headers: {
          'Content-Type': 'multipart/form-data', // 必须是 multipart/form-data
        },
      })
      .then((response) => {
        if (response.data.code === 200) {
          const user = JSON.parse(sessionStorage.getItem('userInfo'))
          user.avatar = response.data.data
          sessionStorage.setItem('userInfo', JSON.stringify(user))
          ElMessage({
            message: '头像上传成功！',
            type: 'success',
          });
          window.location.reload();
        } else {
          ElMessage({
            message: response.data.message || '上传失败，请重试！',
            type: 'error',
          });
        }
      })
      .catch((error) => {
        ElMessage({
          message: error.message || '网络错误，请重试！',
          type: 'error',
        });
      });
      return true;  // 禁止自动上传，使用 axios 上传
    }

    // 修改密码
    const updatePassword = (userId) => {
      if (!passwordForm.oldPassword || !passwordForm.newPassword || !passwordForm.confirmPassword) {
        ElMessage.warning('请填写完整密码信息')
        return
      }
      if (passwordForm.newPassword !== passwordForm.confirmPassword) {
        ElMessage.error('两次输入的新密码不一致')
        return
      }
      passwordForm.userId = userId
      console.log(passwordForm)

      axios.post('/api/user/change/pwd',passwordForm)
      .then(res => {
        if(res.data.code === 200){
          ElMessage.success('密码修改成功!请重新登录')
          passwordForm.oldPassword = ''
          passwordForm.newPassword = ''
          passwordForm.confirmPassword = ''
          sessionStorage.removeItem('userInfo')
          window.location.href = '/'
        }else{
          ElMessage.error(res.data.message)
        }
      }).catch(err => {
        ElMessage.error(err.response.data.message)
      })
    }

    // 取消预约
    const cancelBooking = (ticket) => {
      ElMessageBox.confirm('确定要取消该预约吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        axios.put('/api/ticket/cancel/'+ticket.orderNumber)
        .then(res => {
          if(res.data.code === 200){
            ElMessage.success('订单已取消')
            getTicketList()
          }else{
            ElMessage.error(res.data.message)
          }
        })
        .catch(err => {
          ElMessage.error("取消失败！")
        })
      }).catch(() => {
        ElMessage.info('已取消操作')
      })
    }

    // 删除动态
    const deletePost = (post) => {
      axios.delete('/api/blog//user/del?id='+post.id)
      .then(res => {
        if(res.data.code === 200){
          ElMessage.success('动态已删除')
          getMyPosts()
        }else{
          ElMessage.error(res.data.message)
        }
      })
      .catch(err => {
        ElMessage.error("删除失败！")
      })
    }

    // 获取预约列表
    const getTicketList = () => {
      axios.get('/api/ticket/order/'+userInfo.value.id)
      .then(res => {
          if(res.data.code === 200){
            ticketList.value = res.data.data
          }else{
            ElMessage.error("获取预约列表失败")
          }
      })
      .catch(err => {
        ElMessage.error(err.response.data.message)
      })
    }

    return {
      userInfo,
      passwordForm,
      ticketList,
      myPosts,
      uploadRef,
      handleAvatarClick,
      beforeAvatarUpload,
      updatePassword,
      cancelBooking,
      deletePost,
      Edit,
      Delete,
      getTicketList,
      getMyPosts
    }
  }
}
</script>

<style scoped>
.user-info-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.info-card, .ticket-card, .post-card {
  margin-bottom: 20px;
  border-radius: 8px;
  transition: all 0.3s;
}

.avatar-container {
  text-align: center;
  padding: 20px 0;
}

.hover-effect {
  cursor: pointer;
  transition: transform 0.3s;
}

.hover-effect:hover {
  transform: scale(1.05);
}

.username {
  margin-top: 10px;
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.password-form {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px 0;
}

.header-title {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.post-item {
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.post-item:last-child {
  border-bottom: none;
}

.post-content {
  font-size: 16px;
  line-height: 1.6;
  margin-bottom: 10px;
}

.post-images {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin: 10px 0;
}

.post-image {
  width: 150px;
  height: 150px;
  border-radius: 4px;
  object-fit: cover;
}

.post-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.post-time {
  color: #999;
  font-size: 14px;
}

.el-table {
  margin-top: 10px;
}
</style>